package site.assad.dao;


import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import site.assad.domain.User;

import java.util.List;

/**
 * Author: Al-assad 余林颖
 * E-mail: yulinying_1994@outlook.com
 * Date: 2017/12/15 11:03
 * Description:
 */
@Repository
public class UserDao {

    @Autowired
    private HibernateTemplate hibernateTemplate ;

    //演示insert操作
    public void addUser(User user){
        hibernateTemplate.save(user);
    }

    //演示update操作
    public void updateUser(User user){
        hibernateTemplate.update(user);
    }

    //演示delete操作
    public void deleteUser(User user){
        hibernateTemplate.delete(user);
    }

    //演示查询操作
    public long getUserNum(){
        final String hql = "select count(u.id) from User u ";
        return (Long)hibernateTemplate.iterate(hql).next();
         //or: return ((List<Integer>)hibernateTemplate.find(hql)).get(0);
    }

    public User findUserByName(final String username){
        final String hql = "select u from User u where u.name = ?";
        List<User> result = (List<User>) hibernateTemplate.find(hql,username);
        return (User)result.get(0);
    }

    public List<User> findUserByIcon(final String icon) {
        final String hql = "select u from User u where u.icon = ?";
        return (List<User>) hibernateTemplate.find(hql, icon);
    }

    //使用 executeFind 重写 findUserByName()
    public User findUserByNameV2(final String username){
        User user = hibernateTemplate.execute(new HibernateCallback<User>() {
            @Override
            public User doInHibernate(Session session) throws HibernateException {
                //Hibenate 风格的 POJO 操作代码
                String hql = "select u from User u where u.name = :userName";
                List<User> resultList = session.createQuery(hql)
                        .setParameter("userName",username)
                        .list();
                return resultList.get(0);
            }
        });
        return user;
    }

}
